#include<iostream>
#include<cstdio>
#include<cstring>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstring>
#include<unistd.h>
using namespace std;
void  ChildWrite(int wfd)
{
    char str[1024];
    int count=10;
    while(count--)
    {
        snprintf(str, sizeof(str), "I am child, pid: %d, cnt: %d", getpid(), count);
        write(wfd,str,strlen(str));
        printf("child :%d\n",count);
        sleep(1);
    }
}
void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        sleep(1);
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            cout<<"child say: "<<buffer<<std::endl;
        }
        else if (n==0)
        {
            cout<<"n: "<<n<<endl;
            cout<<"child 退出，我也退出"<<endl;
            /* code */
            break;
        }
        else
        {
            break;
        }
    }
}
int main()
{
    int fds[2];
    int n=pipe(fds);
    if(n<0)
    {
        printf("pipe error\n");
        return 1;
    }
    cout<<"fds[0]: "<<fds[0]<<endl;
    cout<<"fds[1]: "<<fds[1]<<endl;
    //2.创建子进程
    pid_t id=fork();
    if(id==0)
    {
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //3.关闭不要的读写端
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    sleep(1);
    int status=0;
    int ret=waitpid(id,&status,0);
    if(ret>0)
    {
        printf("exit code %d ,exit signal:%d\n",(status>>8)&0xFF,status&0x7F);
       // sleep(5);
    }
    return 0;
}